package com.lj.api.auth;

import com.alibaba.fastjson.JSONObject;
import com.lj.api.auth.exce.IllegalAccessTokenException;
import com.lj.api.auth.exce.OverPeriodException;
import com.lj.api.common.CommUtils;
import com.lj.api.common.Md5Encrypt;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTools{

    public static String generateToken(String sub,String aud,long iat,long exp){
        Map<String,String> header = new HashMap();
        header.put("alg","HS256");
        header.put("typ","JWT");


        String headerStr = CommUtils.encodeBase64(JSONObject.toJSONString(header));
        Map<String,Object> payload = new HashMap();

        //签发方
        payload.put("iss",JwtProperties.iss);

        //接收主体（用户id）
        payload.put("sub",sub);

        //接收方
        payload.put("aud",aud);

        //签发时间
        payload.put("iat",iat);

        //过期时间
        payload.put("exp",exp);


        String payloadStr = CommUtils.encodeBase64(JSONObject.toJSONString(payload));

        String signatrue = Md5Encrypt.md5(headerStr+payloadStr+JwtProperties.secret);

        String token = headerStr+"."+payloadStr+"."+signatrue;
        return token;
    }

    public static boolean checkToken(String tk){
        String[] tks = tk.split("\\.");

        //验证过期时间
        Map map = (Map) JSONObject.parse(CommUtils.dncodeBase64(tks[1]));

        long iat =  Long.valueOf(map.get("iat").toString());
        long exp =  Long.valueOf(map.get("exp").toString());
        long now = new Date().getTime();
        if (iat+exp<now || now<iat){
            throw new OverPeriodException("over period token");
        }

        String signatrue = Md5Encrypt.md5(tks[0]+tks[1]+JwtProperties.secret);

        if (!tks[2].equals(signatrue)){
            throw new IllegalAccessTokenException(" Illegal token");
        }

        return true;
    }

    public static void main(String[] args) {
        String tk = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiYXVkIjoid3h4IiwiaXNzIjoidXAuY3giLCJleHAiOjEyOTYwMDAwMDAsImlhdCI6MTcwNjUzMjUyMjkzNX0=.d49842402ec62eb855d2c7652a1b8ac1";
        String[] tks = tk.split("\\.");

        //验证过期时间
        Map map = (Map) JSONObject.parse(CommUtils.dncodeBase64(tks[1]));

        long iat =  Long.valueOf(map.get("iat").toString());
        long exp =  Long.valueOf(map.get("exp").toString());
        long now = new Date().getTime();
        if (iat+exp<now || now<iat){
            throw new OverPeriodException("over period token");
        }

        String signatrue = Md5Encrypt.md5(tks[0]+tks[1]+JwtProperties.secret);

        if (!tks[2].equals(signatrue)){
            throw new IllegalAccessTokenException(" Illegal token");
        }

    }

}
